//
//  RNAliPayModule.m
//  DoubleConversion
//
//  Created by 坤坤 on 2021/11/27.
//

#import "RNAliPayModule.h"
#import <AlipaySDK/AlipaySDK.h>

@implementation RNAliPayModule
{
    RCTResponseSenderBlock ailCallback;
}
- (dispatch_queue_t)methodQueue
{
    return dispatch_get_main_queue();
}
+ (BOOL)requiresMainQueueSetup {
  return YES;
}
- (instancetype)init
{
  self = [super init];
  if (self) {
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ailPayBack:) name:@"AILPAY_TYPE" object:nil];
  }
  return self;
}
- (void)dealloc
{
  [[NSNotificationCenter defaultCenter] removeObserver:self];
}
/**
 * 支付宝支付回调，从AppDelegate中触发
 */
+(void)applicationOpenURL:(NSURL *)url{
    [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
      NSLog(@"result = %@",resultDic);
      NSNotification *notification = [NSNotification notificationWithName:@"AILPAY_TYPE" object:resultDic];
      [[NSNotificationCenter defaultCenter] postNotification:notification];
    }];
  
}

-(void)ailPayBack:(NSNotification *)nsNotification{
    [self ailCallBackResultStatus:nsNotification.object];
}
/**
 * resultStatus 9000 成功否则失败
 */
- (void)ailCallBackResultStatus:(NSDictionary *)resultDic{
  NSString * resultStatus = (NSString *)[resultDic objectForKey:@"resultStatus"];
  if (ailCallback) {
      ailCallback(@[ resultStatus ]);
      ailCallback = nil;
  }
  
}
RCT_EXPORT_MODULE(aliPay)

RCT_REMAP_METHOD(pay, pay:(NSString *)orderString scheme:(NSString *)scheme event:(RCTResponseSenderBlock)callback) {
   
   ailCallback = callback;
    
   if (orderString) {
     // 调起支付
     [[AlipaySDK defaultService]payOrder:orderString fromScheme:scheme callback:^(NSDictionary *resultDic) {
       NSLog(@"resultss = %@",resultDic);
         // 这里为网页支付回调，如果是APP支付则走AppDelegate
         [self ailCallBackResultStatus:resultDic];
     }];

   }
 }

@end
